using System;
using System.Collections.Generic;
using System.Text;
using Decav.Gatsb.Mobile;
using System.IO;
using Decav.Reality;
using System.Text.RegularExpressions;
using System.Net.Mail;
using Decav.Gatsb.Application;

namespace Decav.Gatsb.MobileProviders
{
    /// <summary>
    /// Parses a message from a <see cref="VerizonServiceProvider"/>
    /// telephone.
    /// </summary>
    public class VerizonMessageParser : IPhoneMessageParser
    {
        #region IPhoneMessageParser Members

        public MobileMessage ParseMailMessage(SmtpMailHeader header, StreamReader messageStream)
        {            
            if (messageStream == null)
                throw new ArgumentNullException("messageStream");

            if (header == null)
                throw new ArgumentNullException("header");

            _header = header;
            string sender = header.Sender.ToString().ToLower();
            PhoneNumber telNum = new PhoneNumber(sender.Split('@')[0]);
            if (sender.Contains("@vtext.com"))
            {
                // SMS
                return ParseSms(messageStream, telNum, header.DateReceived);
            }
            else if (sender.Contains("@vzwpix.com"))
            {
                // MMS
                return ParseMms(messageStream, telNum, header.DateReceived);
            }
            else
            {
                throw new MessageParseException("The message type could not be determined becuase the address was unknown.");
            }
        }

        private SmtpMailHeader _header;

        private MobileMessage ParseMms(StreamReader reader, PhoneNumber telNum, DateTime date)
        {
            StringBuilder messageBody = new StringBuilder();
            List<FileAttachment> attachments = new List<FileAttachment>();

            MultipartReader multipartReader = new MultipartReader(reader, _header.ContentType.Boundry);
            foreach (FileAttachment attachment in multipartReader.Read())
            {
                if (attachment.Type.Type == ContentType.PlainText.Type)
                    messageBody.AppendLine(attachment.ToText());
                else
                    attachments.Add(attachment);
            }


            string message = CleanMessageBody(messageBody.ToString());
            MmsMessage msg = new MmsMessage(_header.Recipient,_header.Sender, telNum, date, message);
            foreach (FileAttachment attach in attachments)
                msg.Attachments.Add(attach);

            MessageParser.RemoveReplies(msg);
            return msg;
        }

        private string CleanMessageBody(string message)
        {
            string[] messageParts = message.Split(new string[] { "This message was sent using PIX-FLIX" }, StringSplitOptions.None);
            return messageParts[0].Trim();
        }

        private MobileMessage ParseSms(StreamReader reader, PhoneNumber telNum, DateTime date)
        {
            StringBuilder builder = new StringBuilder();
            
            // Read the whole body.
            string curLine = null;
            while ((curLine = reader.ReadLine()) != null)
                builder.AppendLine(curLine);

            SmsMessage msg = new SmsMessage(_header.Recipient, _header.Sender, telNum, date, builder.ToString().Trim());
            MessageParser.RemoveReplies(msg);
            return msg;
        }

        #endregion
    }
}
